/**
 * @DefaultClientEndpoint.java  COPYRIGHT xiaojian
 * 
 * Created on 2016年7月20日 下午1:59:24
 */
package xj.toolkit.netty.transport.endpoint;

import java.net.SocketAddress;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

import io.netty.channel.Channel;
import xj.toolkit.netty.transport.ProtocolConstants;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class DefaultClientEndpoint<I> extends AbstractEndpoint<I> implements ClientEndpoint<I> {

	private static final Logger logger = LoggerFactory.getLogger(DefaultClientEndpoint.class);

	private Channel channel = null;

	@Override
	public void start() {

	}

	protected boolean isActive() {
		return channel != null && channel.isActive();
	}

	@Override
	public void send(I target) {
		Preconditions.checkArgument(target != null);

		if (!channel.isOpen()) {
			logger.warn("Channel[{}] ISNOT open. cannot send msg[{}].", channel, target);
			return;
		}

		if (!channel.isWritable()) {
			logger.warn("Channel[{}] ISNOT open. cannot send msg[{}].", channel, target);
			return;
		}

		channel.writeAndFlush(target);
		return;
	}

	@Override
	public void setChannel(Channel channel) {
		Preconditions.checkArgument(channel != null);
		this.channel = channel;
		if (null != objectName && null != mbeanExport) {
			try {
				mbeanExport.getServer().unregisterMBean(objectName);
			} catch (MBeanRegistrationException e) {
				logger.error("setSender:", e);
			} catch (InstanceNotFoundException e) {
				logger.error("setSender:", e);
			}
		}
		if (null != mbeanExport) {
			try {
				objectName = new ObjectName(objectNamePrefix + ",sender="
						+ channel.toString().replaceAll(":", "/").replaceAll(",", "").replaceAll("=>", "-"));
				mbeanExport.registerManagedResource(this, objectName);
			} catch (MalformedObjectNameException e) {
				logger.error("setSender:", e);
			} catch (NullPointerException e) {
				logger.error("setSender:", e);
			}
		}

	}

	@Override
	public void send(Object req, I response) {
		send(response);
	}

	@Override
	public String getProtocol() {
		return ProtocolConstants.PROTOCOL_TCP;
	}

	@Override
	public SocketAddress getRemoteAddress() {
		return channel == null ? null : channel.remoteAddress();
	}

	@Override
	public SocketAddress getLocalAddress() {
		return channel == null ? null : channel.localAddress();
	}

}
